"ui";

importClass(android.content.Intent);
importClass(android.graphics.BitmapFactory);
importClass(android.provider.MediaStore);
importClass(android.webkit.MimeTypeMap);

ui.layout(
  <vertical>
    <button id="btnImg" text="选择图片" />
    <button id="btnAudio" text="选择音频" />
    <button id="btnVideo" text="选择视频" />
    <button id="btnImgAndVideo" text="选择图片和视频" />
    <button id="btnAnyFile" text="选择任意文件" />
    <text textSize="30sp" w="*" gravity="center" textStyle="bold">
      AutoJsPro教程 牙叔
    </text>
    <vertical id="parentView"></vertical>
  </vertical>
);

let imgRequestCode = 1;
let audioRequestCode = 2;
let videoRequestCode = 3;
let imgAndVideoRequestCode = 4;
let imgAnyFileRequestCode = 5;

ui.btnImg.on("click", () => {
  let fileType = "image/*";
  let requestCode = imgRequestCode;
  var intent = new Intent();
  intent.setType(fileType);
  intent.setAction(Intent.ACTION_GET_CONTENT);
  activity.startActivityForResult(intent, requestCode);
});
ui.btnAudio.on("click", () => {
  let requestCode = audioRequestCode;
  let i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
  activity.startActivityForResult(i, requestCode);
});
ui.btnVideo.on("click", () => {
  let fileType = "video/*";
  let requestCode = videoRequestCode;
  var intent = new Intent();
  intent.setType(fileType);
  intent.setAction(Intent.ACTION_GET_CONTENT);
  activity.startActivityForResult(intent, requestCode);
});
ui.btnImgAndVideo.on("click", () => {
  let fileType = "video/* image/*";
  let requestCode = imgAndVideoRequestCode;
  intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
  intent.setType(fileType);
  activity.startActivityForResult(intent, requestCode);
});
ui.btnAnyFile.on("click", () => {
  let fileType = "*/*";
  let requestCode = imgAnyFileRequestCode;
  var intent = new Intent();
  intent.setType(fileType);
  intent.setAction(Intent.ACTION_GET_CONTENT);
  activity.startActivityForResult(intent, requestCode);
});

activity.getEventEmitter().on("activity_result", (requestCode, resultCode, data) => {
  if (resultCode != -1) {
    toastLog("没有选择文件!");
    return false;
  } else {
    var uri = data.getData();
    log("uri: %s", uri.toString());
    let filepath = URIUtils_uriToFile(uri);
    log(filepath);
    var cr = context.getContentResolver();
    switch (requestCode) {
      case imgRequestCode:
        log("图片");
        var bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));
        log("bitmap: %s", bitmap);
        ui.parentView.removeAllViews();
        var childView = ui.inflate(<img></img>, ui.parentView);
        ui.parentView.addView(childView);
        childView.setImageBitmap(bitmap);
        break;
      case audioRequestCode:
        log("音频");
        media.playMusic(filepath);
        toastLog("播放 10 秒钟");
        setTimeout(function () {
          media.stopMusic();
          toastLog("停止播放");
        }, 10000);
        break;
      case videoRequestCode:
        log("视频");
        ui.parentView.removeAllViews();
        var childView = ui.inflate(<VideoView></VideoView>, ui.parentView);
        ui.parentView.addView(childView);
        childView.setVideoPath(filepath);
        childView.start();
        break;
      case imgAndVideoRequestCode:
        log("图片或视频");
        ui.parentView.removeAllViews();

        let fileType = getFileType(filepath);
        if (fileType === "mp4") {
          log("是视频");
          var childView = ui.inflate(<VideoView></VideoView>, ui.parentView);
          ui.parentView.addView(childView);
          childView.setVideoPath(filepath);
          childView.start();
        } else {
          log("是图片");
          var bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));
          var childView = ui.inflate(<img></img>, ui.parentView);
          ui.parentView.addView(childView);
          childView.setImageBitmap(bitmap);
        }
        break;
      case imgAnyFileRequestCode:
        log("任意文件");
        break;
      default:
        log("其他");
        break;
    }
  }
});

// ==========================自定义函数============================================================================

function getFileType(filePath) {
  // 查看文件头请使用软件: HexEditXP
  importClass("java.util.HashMap");
  importClass(java.io.FileInputStream);
  importClass(java.lang.StringBuilder);

  let mFileTypes = new HashMap();
  mFileTypes.put("ffd8ffe000104a464946", "jpg"); //JPEG (jpg)
  mFileTypes.put("89504e470d0a1a0a0000", "png"); //PNG (png)
  mFileTypes.put("47494638396126026f01", "gif"); //GIF (gif)
  mFileTypes.put("49492a00227105008037", "tif"); //TIFF (tif)
  mFileTypes.put("424d228c010000000000", "bmp"); //16色位图(bmp)
  mFileTypes.put("424d8240090000000000", "bmp"); //24位位图(bmp)
  mFileTypes.put("424d8e1b030000000000", "bmp"); //256色位图(bmp)
  mFileTypes.put("41433130313500000000", "dwg"); //CAD (dwg)
  mFileTypes.put("3c21444f435459504520", "html"); //HTML (html)
  mFileTypes.put("3c21646f637479706520", "htm"); //HTM (htm)
  mFileTypes.put("48544d4c207b0d0a0942", "css"); //css
  mFileTypes.put("696b2e71623d696b2e71", "js"); //js
  mFileTypes.put("7b5c727466315c616e73", "rtf"); //Rich Text Format (rtf)
  mFileTypes.put("38425053000100000000", "psd"); //Photoshop (psd)
  mFileTypes.put("46726f6d3a203d3f6762", "eml"); //Email [Outlook Express 6] (eml)
  mFileTypes.put("d0cf11e0a1b11ae10000", "doc"); //MS Excel 注意：word、msi 和 excel的文件头一样
  mFileTypes.put("d0cf11e0a1b11ae10000", "vsd"); //Visio 绘图
  mFileTypes.put("5374616E64617264204A", "mdb"); //MS Access (mdb)
  mFileTypes.put("252150532D41646F6265", "ps");
  mFileTypes.put("255044462d312e350d0a", "pdf"); //Adobe Acrobat (pdf)
  mFileTypes.put("2e524d46000000120001", "rmvb"); //rmvb/rm相同
  mFileTypes.put("464c5601050000000900", "flv"); //flv与f4v相同
  mFileTypes.put("00000020667479706d70", "mp4");
  mFileTypes.put("49443303000000002176", "mp3");
  mFileTypes.put("000001ba210001000180", "mpg"); //
  mFileTypes.put("3026b2758e66cf11a6d9", "wmv"); //wmv与asf相同
  mFileTypes.put("52494646e27807005741", "wav"); //Wave (wav)
  mFileTypes.put("52494646d07d60074156", "avi");
  mFileTypes.put("4d546864000000060001", "mid"); //MIDI (mid)
  mFileTypes.put("504b0304140000000800", "zip");
  mFileTypes.put("526172211a0700cf9073", "rar");
  mFileTypes.put("235468697320636f6e66", "ini");
  mFileTypes.put("504b03040a0000000000", "jar");
  mFileTypes.put("4d5a9000030000000400", "exe"); //可执行文件
  mFileTypes.put("3c25402070616765206c", "jsp"); //jsp文件
  mFileTypes.put("4d616e69666573742d56", "mf"); //MF文件
  mFileTypes.put("3c3f786d6c2076657273", "xml"); //xml文件
  mFileTypes.put("494e5345525420494e54", "sql"); //xml文件
  mFileTypes.put("7061636b616765207765", "java"); //java文件
  mFileTypes.put("406563686f206f66660d", "bat"); //bat文件
  mFileTypes.put("1f8b0800000000000000", "gz"); //gz文件
  mFileTypes.put("6c6f67346a2e726f6f74", "properties"); //bat文件
  mFileTypes.put("cafebabe0000002e0041", "class"); //bat文件
  mFileTypes.put("49545346030000006000", "chm"); //bat文件
  mFileTypes.put("04000000010000001300", "mxp"); //bat文件
  mFileTypes.put("504b0304140006000800", "docx"); //docx文件
  mFileTypes.put("d0cf11e0a1b11ae10000", "wps"); //WPS文字wps、表格et、演示dps都是一样的
  mFileTypes.put("6431303a637265617465", "torrent");

  mFileTypes.put("6D6F6F76", "mov"); //Quicktime (mov)
  mFileTypes.put("FF575043", "wpd"); //WordPerfect (wpd)
  mFileTypes.put("CFAD12FEC5FD746F", "dbx"); //Outlook Express (dbx)
  mFileTypes.put("2142444E", "pst"); //Outlook (pst)
  mFileTypes.put("AC9EBD8F", "qdf"); //Quicken (qdf)
  mFileTypes.put("E3828596", "pwl"); //Windows Password (pwl)
  mFileTypes.put("2E7261FD", "ram"); //Real Audio (ram)
  mFileTypes.put("null", null); //null

  function getFileType(filePath) {
    filePath = java.lang.String(filePath);
    let keySearch = getFileHeader(filePath);
    fileType = mFileTypes.get(keySearch);
    if (!fileType) {
      let keyList = mFileTypes.keySet().iterator();
      let keySearchChild = keySearch.substring(10, keySearch.length);
      while (keyList.hasNext()) {
        let key = keyList.next();
        key = java.lang.String(key);
        if (key.contains(keySearchChild)) {
          let fileSuffix = mFileTypes.get(key);
          return fileSuffix;
        }
      }
    }
    return fileType;
  }
  //获取文件头信息
  function getFileHeader(filePath) {
    let is = null;
    let value = null;
    try {
      let is = new FileInputStream(filePath);
      let b = util.java.array("byte", 10);
      is.read(b, 0, b.length);
      value = bytesToHexString(b);
    } catch (e) {
      log(e);
    } finally {
      if (null != is) {
        try {
          is.close();
        } catch (e) {
          log(e);
        }
      }
    }
    return value;
  }

  // arr =["0","0","0","18","66","74","79","70","6d","70"]
  function bytesToHexString(src) {
    let arr = [];
    let stringBuilder = new StringBuilder();
    for (let i = 0; i < src.length; i++) {
      let v = src[i] & 0xff;
      let hv = java.lang.Integer.toHexString(v);
      // hv = java.lang.String()
      if (hv.length < 2) {
        stringBuilder.append("0");
      }
      stringBuilder.append(hv);
      arr.push(hv);
    }
    return stringBuilder.toString();
  }
  let fileType = getFileType(filePath);
  return fileType;
}

function URIUtils_uriToFile(uri) {
  //Source : https://www.cnblogs.com/panhouye/archive/2017/04/23/6751710.html
  var r = null,
    cursor,
    column_index,
    selection = null,
    selectionArgs = null,
    isKitKat = android.os.Build.VERSION.SDK_INT >= 19,
    docs;
  if (uri.getScheme().equalsIgnoreCase("content")) {
    if (isKitKat && android.provider.DocumentsContract.isDocumentUri(activity, uri)) {
      if (String(uri.getAuthority()) == "com.android.externalstorage.documents") {
        docs = String(android.provider.DocumentsContract.getDocumentId(uri)).split(":");
        if (docs[0] == "primary") {
          return android.os.Environment.getExternalStorageDirectory() + "/" + docs[1];
        }
      } else if (String(uri.getAuthority()) == "com.android.providers.downloads.documents") {
        uri = android.content.ContentUris.withAppendedId(
          android.net.Uri.parse("content://downloads/public_downloads"),
          parseInt(android.provider.DocumentsContract.getDocumentId(uri))
        );
      } else if (String(uri.getAuthority()) == "com.android.providers.media.documents") {
        docs = String(android.provider.DocumentsContract.getDocumentId(uri)).split(":");
        if (docs[0] == "image") {
          uri = android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        } else if (docs[0] == "video") {
          uri = android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
        } else if (docs[0] == "audio") {
          uri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        }
        selection = "_id=?";
        selectionArgs = [docs[1]];
      }
    }
    try {
      cursor = activity.getContentResolver().query(uri, ["_data"], selection, selectionArgs, null);
      if (cursor && cursor.moveToFirst()) {
        r = String(cursor.getString(cursor.getColumnIndexOrThrow("_data")));
      }
    } catch (e) {
      log(e);
    }
    if (cursor) cursor.close();
    return r;
  } else if (uri.getScheme().equalsIgnoreCase("file")) {
    return String(uri.getPath());
  }
  return null;
}
